<template>
  <div class="main">
    <div class="search">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-button type="success" size="small" @click="form = { status: true }; dialogShow = true">添加</el-button>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="search.name" size="small" placeholder="名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="search.description" size="small" placeholder="备注" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="small" @click="searchClick">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list">
      <el-table
          :data="data"
          stripe
          row-key="id"
          style="width: 100%">
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="icon" label="图标">
          <template slot-scope="scope">
            <el-image :src="scope.row.icon" fit="contain" style="height: 60px;">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" style="font-size: 60px;"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="parentId" label="父级">
          <template slot-scope="scope">
            {{ scope.row.parent ? scope.row.parent.name : '目录' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="170px">
          <template slot-scope="scope">
            <el-button type="primary" @click="form = {...scope.row}; dialogShow = true">编辑</el-button>
            <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
        :title="form.id ? '修改' : '添加'"
        :visible.sync="dialogShow"
        width="900px"
        @close="dialogClose"
    >
      <el-form :model="form" ref="form" :rules="rules" label-position="left" label-width="80px" size="medium"
               @submit.native.prevent>
        <el-row>
          <el-col :span="12" class="grid-cell">
            <el-form-item label="名称" prop="name" class="required">
              <el-input v-model="form.name" type="text" clearable></el-input>
            </el-form-item>
            <el-form-item label="父级" prop="parentId" class="required">
              <treeselect
                v-model="form.parentId"
                :multiple="false"
                :options="[{id: 0, name: '目录', children: data}]"
                :normalizer="(node) => {return {
                              id: node.id,
                              label: node.name,
                              children: node.children,
                            }}"
                @select="treeSelect"
              >
              </treeselect>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" type="number" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" class="grid-cell">
            <el-form-item label="图标" prop="icon">
              <el-upload :headers="{ token: token }" :file-list="form.icon ? [{name: '图标', url: form.icon}] : []" :data="form.icon" :on-success="iconSuccess"
                         action="/upload/image" list-type="picture-card" show-file-list :limit="1"> <template #default><i
                  class="el-icon-plus"></i></template></el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" rows="5"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">保存</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "../util/auth";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: "GoodsType",
  components: { Treeselect },
  data() {
    return {
      search: {},
      dialogShow: false,
      form: {},
      data: [],
      rules: {
        name: [
            {
            required: true,
            message: '名称不能为空',
          },
          {
            min: 1,
            max: 300,
            message: '名称长度在1-300位之间',
            trigger: 'blur'
          },
          {
            validator: (rule, val, cb) => {
              let url = `goods-type/repeat?name=${val}`
              if (this.form.id) url += `&id=${this.form.id}`
              this.$http.get(url).then(res => {
                if (res.code === 200) {
                  if (res.data) {
                    return cb(new Error('用户名已存在！'))
                  }
                  cb()
                }
              })
            },
            trigger: 'blur'
          }
        ],
        parentId: [{
          required: true,
          message: '父级不能为空',
        }],
        description: [
          {
            min: 0,
            max: 800,
            message: '备注长度在3-800位之间',
            trigger: 'blur'
          }
        ]
      },
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      this.$http.post(`goods-type/tree`, this.search).then(res => {
        if (res.code === 200) {
          this.data = res.data
        }
      })
    },
    searchClick() {
      this.pageNo = 1;
      this.getData()
    },
    dialogClose() {
      this.form = { status: true }
      this.$refs['form'].clearValidate()
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.$http.put(`goods-type`, this.form).then(res => {
              if(res.code === 200) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          } else {
            this.$http.post(`goods-type`, this.form).then(res => {
              if(res.code === 200) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          }
        }
      });
    },
    del(id) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`goods-type/${id}`).then(res => {
          if (res.code === 200) {
            this.getData()
            this.$Message.success(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    iconSuccess(result) {
      if (result.errno === 0) {
        this.form.icon = result.data.url
      }
    },
    treeSelect(node) {
      if (node.id === 0) this.form.deep = 1;
      else this.form.deep = node.deep + 1
    }
  },
  computed: {
    token() {
      return getToken()
    }
  }
}
</script>

<style scoped>

</style>
